export default function (el, binding) {
  let divTag = el;
  let form = binding.value || {};
  if(divTag) {
    if(form.status === '1') {
      divTag.style.background = 'transparent';
      return
    }
    const {bgImage, bgSize} = setBackgoundColor()
    divTag.style.backgroundImage = bgImage;
    divTag.style.backgroundSize = bgSize;
  }
  function setBackgoundColor() {
    const bgImage = `url(${getBase64Background({})})`;
    const bgSize = `${form.spaceX}px ${form.spaceY}px`
    return {bgImage, bgSize}
  }
  function getBase64Background(props) {
    console.log(form, 'form');
    const {
      rotate = form.angel,
      width = 200 + (form.offsetX)*1 + (form.spaceX)*1,
      height = 50 + (form.offsetY)*1 + (form.spaceY)*1,
      text = form.text,
      waterTime = form.waterTime,
      fontSize = form.fontSize,
      fontFamily = form.fontFamily,
      fillStyle = form.color,
      opacity = form.opacity / 100,
      position = { x: (form.offsetX)*1, y: (form.offsetY)*1 },
      waterTimePosition = { x: (form.offsetX)*1, y: form.offsetY*1 + 20 },
    } = props;
    const image = new Image();
    image.crossOrigin = 'Anonymous';
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    canvas.width = width;
    canvas.height = height;
    context.font = `${fontSize}px ${fontFamily}`;
    context.fillStyle = fillStyle;
    context.textAlign = 'left';
    context.textBaseline = 'top';
    context.globalAlpha = opacity;
    const fontTextObj = context.measureText(text, `${fontSize}px ${fontFamily}`);
    const dateTextObj = context.measureText(waterTime, `${fontSize}px ${fontFamily}`);
    const fontTextObjHeight = fontTextObj.actualBoundingBoxAscent + fontTextObj.actualBoundingBoxDescent;
    const dateTextObjHeight = dateTextObj.actualBoundingBoxAscent + dateTextObj.actualBoundingBoxDescent;
    const newMax = Math.ceil(Math.max(fontTextObj.width, dateTextObj.width));
    let fontHeight = Math.ceil(position.y + fontTextObjHeight / 2) ;
    if (dateTextObjHeight > 0) {
      fontHeight = Math.ceil((waterTimePosition.y  + dateTextObjHeight - position.y) / 2 + position.y) ;
    }
    context.translate((position.x + newMax / 2), fontHeight);
    context.rotate(rotate * Math.PI / 180);
    context.translate(-(position.x + newMax / 2), -fontHeight);
    if(text) context.fillText(text, position.x, position.y);
    if(waterTime) context.fillText(waterTime, 1.4*waterTimePosition.x, 1.4*waterTimePosition.y);
    return canvas.toDataURL('image/png');
  }
}